<template>
  <div class="table expand">
    <el-table
      ref="expandTableRef"
      border
      :data="dataSource"
      v-loading="loading"
      @select="onSelect"
      @select-all="onSelect"
      :row-style="{ height: 54 + 'px' }"
      :cell-style="{ padding: 0 + 'px' }"
      :show-summary="showSummary"
      :summary-method="summaryMethod"
      :sum-text="sumText"
      :fit="true"
    >
      <!-- 多选 -->
      <el-table-column v-if="selection" type="selection" width="55" align="center" />
      <!-- 序号 -->
      <el-table-column
        v-if="index"
        type="index"
        :label="$t('lang.table.index')"
        align="center"
        :index="handleIndex"
      />
      <column v-for="column of columns" :key="column.key" :item="column" :options="options" />
      <!-- 操作列 -->
      <el-table-column v-if="$slots.expandOperate" :label="$t('lang.operate.name')" align="center" min-width="30">
        <template #default="scope">
          <div class="operate">
            <slot :row="scope.row" name="expandOperate" />
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- <el-pagination
      class="pagination"
      v-if="pagination"
      v-model:current-page="pagination.pageNum"
      :page-size="pagination.pageSize"
      :page-sizes="pageSizes"
      layout="sizes, total, prev, pager, next, jumper"
      :total="pagination.total"
      background
      @current-change="changePage"
      @size-change="handleSizeChange"
      style="margin: 10px 0 0 0"
    /> -->
  </div>
</template>
<script lang="ts">
import { defineComponent, PropType, ref, watch, nextTick, onMounted, computed } from 'vue'
import { DataSource, Columns, Pagination } from './types'
import Column from './Column.vue'
import { ObjectType } from 'typings/interfaces'
import { Options } from '../Form/types'
import { Optional } from 'typings/util'
import { intersectionBy, forEach, differenceBy } from 'lodash'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'

export * from './types'

type Sort = Optional<Pagination>

interface Order {
  order: 'ascending' | 'descending' | null
  prop: string
}

export default defineComponent({
  emits: {
    'change-page': null,
    'update:selectedRows': null,
    'size-change': null,
  },
  components: {
    Column,
  },
  props: {
    loading: {
      type: Boolean,
      required: true,
    },
    columns: {
      type: Array as PropType<Columns>,
      required: true,
    },
    dataSource: {
      type: Array as PropType<DataSource>,
      required: true,
    },
    pagination: {
      type: Object as PropType<Pagination>,
      required: true,
    },
    // 非必填
    index: {
      type: Boolean,
      default: true,
    },
    selection: {
      type: Boolean,
      default: false,
    },
    selectedRows: {
      type: Array as PropType<ObjectType[]>,
      default: [],
    },
    defaultSelectedRows: {
      type: Array as PropType<ObjectType[]>,
      default: [],
    },
    options: {
      type: Object as PropType<Options>,
      default: () => ({}),
    },
    maxHeight: {
      type: Number,
      default: 500,
    },
    valuePath: {
      type: String,
      default: 'id',
    },
    sort: {
      type: Function as PropType<(obj: Sort) => Promise<ObjectType[]>>,
      required: true,
    },
    showSummary: {
      type: Boolean,
      default: false,
    },
    summaryMethod: {
      type: Function as PropType<(obj: ObjectType) => Promise<any[]>>,
      default: null,
    },
    sumText: {
      type: String,
      default: '合计',
    },
    sizeChange: {
      type: Function as PropType<(obj: ObjectType) => Promise<any[]>>,
      default: null,
    },
    expandKey: {
      type: String,
      default: null,
    },
    expandColumns: {
      type: Array,
      default: () => [],
    },
  },
  setup(props, { emit }) {
    const store = useStore()
    const router = useRouter()
    const tableRef = ref<ObjectType | null>(null)
    const toggleSelection = (selectedRows: ObjectType[], toggleStatus: boolean) =>
      forEach(selectedRows, (row) => tableRef?.value?.toggleRowSelection(row, toggleStatus))

    // 初始已选择行
    onMounted(() => {
      //   toggleSelection(intersectionBy(props.dataSource, props.selectedRows, props.valuePath), true)
    })
    // 监听数据发生变化
    watch(
      () => props.dataSource,
      () =>
        nextTick().then(() =>
          toggleSelection(
            intersectionBy(props.dataSource, props.selectedRows, props.valuePath),
            true
          )
        )
    )

    // 选择项发生变化
    watch(
      () => props.selectedRows,
      () =>
        toggleSelection(differenceBy(props.dataSource, props.selectedRows, props.valuePath), false)
    )

    // 多选,选择行
    const onSelect = (rows: ObjectType[]) => {
      const initRows = differenceBy(
        props.selectedRows,
        intersectionBy(props.dataSource, props.selectedRows, props.valuePath),
        props.valuePath
      )
      emit('update:selectedRows', [...initRows, ...rows])
    }

    const handleIndex = (index: number) => {
      return index + 1
    }

    const pageSizes = computed(() => store.state.global.pageSizes)
    const handleSizeChange = (val: number) => {
      store.commit('savePageSize', val)
      emit('size-change', val)
    }
    const serviceFacility = {
      tollGateNumber: 3,
      serviceAreaNum: 4,
      parkingArea: 5,
      gasStation: 6,
    }

    return {
      tableRef,
      onSelect,
      changePage: (page: number) => emit('change-page', page),
      handleIndex,
      handleSizeChange,
      pageSizes,
    }
  },
})
</script>
<style scoped lang="scss">
.table {
  display: flex;
  flex-direction: column;
  height: 100%;
  flex: 1;
  :global(.el-pagination) {
    text-align: end;
  }
  .pagination {
    margin-top: auto;
  }
}

.expand {
  width: 100%;
  padding: 20px;
  background: #fff;
}
</style>
